﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AiXiu.Model;
using AiXiu.BLL;
using AiXiu.Common;

namespace AiXiu.WebSite
{
    public partial class UpdateHeadPortrait : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //第一次加载页面
            if (!IsPostBack)
            {
                //读取用户信息
                TBUsers user = IdentityManager.ReadUser();
                if (string.IsNullOrEmpty(user.Avatar))
                {
                    Image1.ImageUrl = "~/imgs/avatar.jpg";
                }
                else
                {
                    Image1.ImageUrl = user.Avatar;
                }
                btnSave.Visible = false;
            }
        }
        //上传头像
        protected void btnUpload_Click(object sender, EventArgs e)
        {
            //判断是否上传了文件
            if (FileUpload1.HasFile)
            {
                //指定上传文件在服务器上的保存路径
                string savePath = Server.MapPath("~/Picture/");
                //检查服务器上是否存在这个物理路径，如果不存在，则创建
                if (!System.IO.Directory.Exists(savePath))
                {
                    System.IO.Directory.CreateDirectory(savePath);
                }
                //保存文件
                FileUpload1.SaveAs(savePath + FileUpload1.FileName);
                //展示图片
                Image1.ImageUrl = "/Picture/" + FileUpload1.FileName;
                btnSave.Visible = true;
            }           
        }
        //更新头像
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //读取用户信息
            TBUsers user = IdentityManager.ReadUser();
            user.Avatar = Image1.ImageUrl;

            //调用方法更新头像
            UserBLL userBLL = new UserBLL();
            OperResult<TBUsers> result = userBLL.UpdateHeadPortrait(user);
            if (result.StatusCode == StatusCode.Succeed)
            {
                // 读取缓存用户资料
                TBUsers userCookie = IdentityManager.ReadUser();
                userCookie.Avatar = user.Avatar;
                // 更新缓存用户资料
                IdentityManager.SaveUser(userCookie);
                // 跳转到个人页
                this.Redirect("editSuccess", "MyInfo.aspx");
            }
            else
            {
                this.Alert("editFaied", result.Message);
            }
        }
    }
}